#pragma once
#include "requestor.hpp"
#include <unordered_map>

namespace zl
{
    namespace client
    {
        // 服务提供者
        // 只要一个服务注册接口，连接注册中心
        class Provider
        {
        public:
            using ptr = std::shared_ptr<Provider>;

            Provider(const Requestor::ptr &requestor)
                : _requestor(requestor)
            {
            }

            bool registryMethod(const BaseConnection::ptr &conn, const std::string &method, const Address &host)
            {
                // 只要向注册中心发送消息就可以了
                auto req_msg = MessageFactory::create<ServiceRequest>();
                req_msg->setMethod(method);
                req_msg->setId(UUID::uuid());
                req_msg->setOptype(ServiceOptype::SERVICE_REGISTRY);
                req_msg->setHost(host);
                req_msg->setMType(MType::REQ_SERVICE);

                BaseMessage::ptr rsp_msg;
                // 同步
                bool ret = _requestor->send(conn, req_msg, rsp_msg);
                if (ret == false)
                {
                    ELOG("%s 服务注册失败", method.c_str());
                    return false;
                }

                auto service_rsp = std::dynamic_pointer_cast<ServiceResponse>(rsp_msg);
                if (service_rsp == nullptr)
                {
                    ELOG("响应类型向下转换失败");
                    return false;
                }

                if (service_rsp->rcode() != RCode::RECODE_OK)
                {
                    ELOG("服务注册失败,原因: %s", errReason(service_rsp->rcode()).c_str());
                    return false;
                }

                return true;
            }

        private:
            client::Requestor::ptr _requestor;
        };

        // 管理方法和主机
        class MethodHost
        {
        public:
            using ptr = std::shared_ptr<MethodHost>;
            MethodHost()
            {
                _idx = 0;
            }

            MethodHost(const std::vector<Address> &hosts)
                : _hosts(hosts), _idx(0)
            {
            }

            void appendHost(const Address &host)
            {
                // 中途收到了服务上线请求后被调用
                std::unique_lock<std::mutex> lock(_mutex);
                _hosts.push_back(host);
            }

            void removeHost(const Address &host)
            {
                // 中途收到了服务下线请求后被调用
                std::unique_lock<std::mutex> lock(_mutex);
                for (auto it = _hosts.begin(); it != _hosts.end(); ++it)
                {
                    if (*it == host)
                    {
                        _hosts.erase(it);
                        break;
                    }
                }
            }

            // 轮转选择
            Address chooseHost()
            {
                std::unique_lock<std::mutex> lock(_mutex);
                size_t pos = _idx++ % _hosts.size();
                return _hosts[pos];
            }

            bool empty()
            {
                std::unique_lock<std::mutex> lock(_mutex);
                return _hosts.empty();
            }

        private:
            std::mutex _mutex;
            std::vector<Address> _hosts;
            int _idx; // RR轮转索引
        };

        class Discoverer
        {
        public:
            using ptr = std::shared_ptr<Discoverer>;
            using offlinCallback = std::function<void(const Address &)>;

            Discoverer(const Requestor::ptr &requestor, const offlinCallback &offline_callback)
                : _requestor(requestor), _offline_callback(offline_callback)
            {
            }

            // 服务发现
            bool serviceDiscover(const BaseConnection::ptr &conn, const std::string &method, Address &host)
            {
                {
                    // 当前所保管的提供者信息存在，则直接返回地址
                    std::unique_lock<std::mutex> lock(_mutex);
                    auto it = _method_hosts.find(method);
                    if (it != _method_hosts.end())
                    {
                        if (it->second->empty() == false)
                        {
                            host = it->second->chooseHost();
                            return true;
                        }
                    }
                }

                // 当前服务的提供者为空
                // 发送请求
                auto req_msg = MessageFactory::create<ServiceRequest>();
                req_msg->setMethod(method);
                req_msg->setId(UUID::uuid());
                req_msg->setOptype(ServiceOptype::SERVICE_DISCOVERY);
                req_msg->setHost(host);
                req_msg->setMType(MType::REQ_SERVICE);

                BaseMessage::ptr rsp_msg;
                // 同步
                bool ret = _requestor->send(conn, req_msg, rsp_msg);
                if (ret == false)
                {
                    ELOG("服务发现失败");
                    return false;
                }

                auto service_rsp = std::dynamic_pointer_cast<ServiceResponse>(rsp_msg);
                if (service_rsp == nullptr)
                {
                    ELOG("服务发现失败,响应类型向下转换失败");
                    return false;
                }

                if (service_rsp->rcode() != RCode::RECODE_OK)
                {
                    ELOG("服务发现失败,原因: %s", errReason(service_rsp->rcode()).c_str());
                    return false;
                }

                std::unique_lock<std::mutex> lock(_mutex);
                auto method_host = std::make_shared<MethodHost>(service_rsp->hosts());
                if (method_host->empty())
                {
                    ELOG("%s 服务发现失败,没有能提供服务的主机", method.c_str());
                    return false;
                }

                host = method_host->chooseHost();
                _method_hosts[method] = method_host;
                return true;
            }

            // 这个接口是提供给Dispatcher模块进行服务上线下线请求处理的回调函数
            void onServiceRequest(const BaseConnection::ptr &conn, const ServiceRequest::ptr &msg)
            {
                // 1. 判断是上线还是下线请求，如果都不是那就不用处理了
                auto optype = msg->optype();
                std::string method = msg->method();
                std::unique_lock<std::mutex> lock(_mutex);

                if (optype == ServiceOptype::SERVICE_ONLINE)
                {
                    // 2. 上线请求：找到MethodHost，向其中新增一个主机地址
                    auto it = _method_hosts.find(method);
                    if (it == _method_hosts.end())
                    {
                        // 添加新服务和新服务提供者
                        auto method_host = std::make_shared<MethodHost>();
                        method_host->appendHost(msg->host());
                        _method_hosts[method] = method_host;
                    }
                    else
                    {
                        it->second->appendHost(msg->host());
                    }
                }
                else if (optype == ServiceOptype::SERVICE_OFFLINE)
                {
                    // 3. 下线请求：找到MethodHost，从其中删除一个主机地址
                    auto it = _method_hosts.find(method);
                    if (it == _method_hosts.end())
                    {
                        return;
                    }
                    it->second->removeHost(msg->host());
                    _offline_callback(msg->host());
                }
            }

        private:
            offlinCallback _offline_callback;
            std::mutex _mutex;
            std::unordered_map<std::string, MethodHost::ptr> _method_hosts;
            Requestor::ptr _requestor;
        };
    }
}